/*
 * @Author: 吴世扬 18368095041@163.com
 * @Date: 2025-02-11 16:28:58
 * @LastEditors: 吴世扬 18368095041@163.com
 * @LastEditTime: 2025-02-24 08:57:17
 * @FilePath: /vue3-admin-server/src/guards/auth.guard.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import {
    Injectable,
    CanActivate,
    ExecutionContext,
    HttpException,
    HttpStatus
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import type { Observable } from 'rxjs';

@Injectable()
export class AuthGuard implements CanActivate {
    constructor(private readonly jwtService: JwtService) {}

    canActivate(
        context: ExecutionContext
    ): boolean | Promise<boolean> | Observable<boolean> {
        const request = context.switchToHttp().getRequest<HwRequest>();
        const token = request.headers.token
            ? request.headers.token
            : request.cookies.token
              ? request.cookies.token
              : request.query.token
                ? (request.query.token as string)
                : '';
        if (!token) {
            throw new HttpException('Token not found', HttpStatus.UNAUTHORIZED);
        }
        try {
            const payload: JwtTokenPayload = this.jwtService.verify(token);
            request['tokenPayload'] = payload;
        } catch {
            throw new HttpException('Invalid token', HttpStatus.UNAUTHORIZED);
        }
        return true;
    }
}
